package com.ruoyi.functiontest.controller;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.functiontest.domain.TollBridgeStatTest;
import com.ruoyi.functiontest.service.ITollBridgeStatTestService;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 收费桥梁统计测试Controller
 * 
 * @author ruoyi
 * @date 2025-09-24
 */
@RestController
@RequestMapping("/functiontest/TollBridgeStatTest")
public class TollBridgeStatTestController extends BaseController
{
    @Autowired
    private ITollBridgeStatTestService tollBridgeStatTestService;

    /**
     * 查询收费桥梁统计测试列表
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollBridgeStatTest:list')")
    @GetMapping("/list")
    public AjaxResult list(TollBridgeStatTest tollBridgeStatTest)
    {
        List<TollBridgeStatTest> list = tollBridgeStatTestService.selectTollBridgeStatTestList(tollBridgeStatTest);
        
        // 判断是否有搜索条件，如果有则构建树形结构返回
        boolean hasSearchCondition = tollBridgeStatTest.getRoadName() != null && !tollBridgeStatTest.getRoadName().isEmpty() ||
                                   tollBridgeStatTest.getNodeName() != null && !tollBridgeStatTest.getNodeName().isEmpty();
        
        if (hasSearchCondition) {
            // 有搜索条件时，构建树形结构返回，包含匹配节点及其所有子节点
            List<TollBridgeStatTest> treeList = buildTree(list);
            return success(treeList);
        } else {
            // 无搜索条件时，返回扁平列表
            return success(list);
        }
    }

    /**
     * 导出收费桥梁统计测试列表
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollBridgeStatTest:export')")
    @Log(title = "收费桥梁统计测试", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TollBridgeStatTest tollBridgeStatTest)
    {
        List<TollBridgeStatTest> list = tollBridgeStatTestService.selectTollBridgeStatTestList(tollBridgeStatTest);
        ExcelUtil<TollBridgeStatTest> util = new ExcelUtil<TollBridgeStatTest>(TollBridgeStatTest.class);
        util.exportExcel(response, list, "收费桥梁统计测试数据");
    }

    /**
     * 获取收费桥梁统计测试详细信息
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollBridgeStatTest:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tollBridgeStatTestService.selectTollBridgeStatTestById(id));
    }

    /**
     * 新增收费桥梁统计测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollBridgeStatTest:add')")
    @Log(title = "收费桥梁统计测试", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TollBridgeStatTest tollBridgeStatTest)
    {
        return toAjax(tollBridgeStatTestService.insertTollBridgeStatTest(tollBridgeStatTest));
    }

    /**
     * 修改收费桥梁统计测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollBridgeStatTest:edit')")
    @Log(title = "收费桥梁统计测试", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TollBridgeStatTest tollBridgeStatTest)
    {
        return toAjax(tollBridgeStatTestService.updateTollBridgeStatTest(tollBridgeStatTest));
    }

    /**
     * 删除收费桥梁统计测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollBridgeStatTest:remove')")
    @Log(title = "收费桥梁统计测试", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        for (Long id : ids) {
            if (tollBridgeStatTestService.hasChildById(id)) {
                return error("节点存在子节点，请先删除子节点后再删除父节点");
            }
        }
        return toAjax(tollBridgeStatTestService.deleteTollBridgeStatTestByIds(ids));
    }
    
    /**
     * 导入收费桥梁统计测试数据
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollBridgeStatTest:import')")
    @Log(title = "收费桥梁统计测试", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<TollBridgeStatTest> util = new ExcelUtil<TollBridgeStatTest>(TollBridgeStatTest.class);
        List<TollBridgeStatTest> importList = util.importExcel(file.getInputStream());
        
        // 调用服务层的导入方法
        String message = tollBridgeStatTestService.importTollBridgeStatTest(importList, updateSupport);
        return success(message);
    }

    /**
     * 导入模板下载
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollBridgeStatTest:import')")
    @GetMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        List<TollBridgeStatTest> templateList = new ArrayList<>();
        
        TollBridgeStatTest example1 = new TollBridgeStatTest();
        example1.setId(1L);
        example1.setRoadName("G1京哈高速");
        example1.setNodeName("北京-沈阳段");
        example1.setLeftLength(new java.math.BigDecimal("100.50"));
        example1.setRightLength(new java.math.BigDecimal("120.75"));
        example1.setAvgLength(new java.math.BigDecimal("110.63"));
        example1.setRemark("示例数据1");
        templateList.add(example1);
        
        TollBridgeStatTest example2 = new TollBridgeStatTest();
        example2.setId(2L);
        example2.setRoadName("G1京哈高速");
        example2.setNodeName("沈阳-哈尔滨段");
        example2.setLeftLength(new java.math.BigDecimal("150.25"));
        example2.setRightLength(new java.math.BigDecimal("160.80"));
        example2.setAvgLength(new java.math.BigDecimal("155.53"));
        example2.setRemark("示例数据2");
        templateList.add(example2);
        
        TollBridgeStatTest example3 = new TollBridgeStatTest();
        example3.setId(3L);
        example3.setRoadName("G2京沪高速");
        example3.setNodeName("北京-上海段");
        example3.setLeftLength(new java.math.BigDecimal("200.00"));
        example3.setRightLength(new java.math.BigDecimal("210.50"));
        example3.setAvgLength(new java.math.BigDecimal("205.25"));
        example3.setRemark("示例数据3");
        templateList.add(example3);
        
        TollBridgeStatTest example4 = new TollBridgeStatTest();
        example4.setId(4L);
        example4.setRoadName("G2京沪高速");
        example4.setNodeName("上海-南京段");
        example4.setLeftLength(new java.math.BigDecimal("180.75"));
        example4.setRightLength(new java.math.BigDecimal("190.20"));
        example4.setAvgLength(new java.math.BigDecimal("185.48"));
        example4.setRemark("示例数据4");
        templateList.add(example4);
        
        ExcelUtil<TollBridgeStatTest> util = new ExcelUtil<TollBridgeStatTest>(TollBridgeStatTest.class);
        util.exportExcel(response, templateList, "收费桥梁统计测试导入模板");
    }
    
    /**
     * 实测单位批量审核
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollBridgeStatTest:fieldAudit')")
    @Log(title = "收费桥梁统计测试", businessType = BusinessType.UPDATE)
    @PostMapping("/fieldAudit/batch")
    public AjaxResult fieldAuditBatch()
    {
        try {
            // 批量更新所有记录的review1字段为0
            int updatedCount = tollBridgeStatTestService.updateReview1ToZero();
            System.out.println("实测单位批量审核完成，更新记录数：" + updatedCount);
            return success("实测单位批量审核成功，共更新" + updatedCount + "条记录");
        } catch (Exception e) {
            System.err.println("实测单位批量审核失败：" + e.getMessage());
            return error("实测单位批量审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 业主批量审核
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollBridgeStatTest:ownerAudit')")
    @Log(title = "收费桥梁统计测试", businessType = BusinessType.UPDATE)
    @PostMapping("/ownerAudit/batch")
    public AjaxResult ownerAuditBatch(@RequestBody Map<String, Object> params)
    {
        try {
            Long deptId = params.get("deptId") != null ? Long.valueOf(params.get("deptId").toString()) : null;
            Long roleId = params.get("roleId") != null ? Long.valueOf(params.get("roleId").toString()) : null;
            
            System.out.println("业主批量审核 - 审核所有数据，deptId: " + deptId + ", roleId: " + roleId);
            
            // 1. 校验所有数据的review1字段是否都为0
            boolean allReview1Zero = tollBridgeStatTestService.checkAllReview1IsZero();
            if (!allReview1Zero) {
                return error("业主批量审核失败：存在未通过实测单位审核的数据，请先完成实测单位审核");
            }
            
            // 2. 构建查询条件
            TollBridgeStatTest queryCondition = new TollBridgeStatTest();
            queryCondition.setDeptId(deptId);
            queryCondition.setRoleId(roleId);
            
            // 3. 从params中提取查询条件
            if (params.get("roadName") != null) {
                queryCondition.setRoadName(params.get("roadName").toString());
            }
            if (params.get("nodeName") != null) {
                queryCondition.setNodeName(params.get("nodeName").toString());
            }
            
            // 4. 根据条件批量更新业主审核状态
            int updatedCount = tollBridgeStatTestService.updateReview2ToZeroByCondition(queryCondition);
            
            System.out.println("业主批量审核完成，更新记录数：" + updatedCount);
            return success("业主批量审核成功，共更新" + updatedCount + "条记录");
        } catch (Exception e) {
            System.err.println("业主批量审核失败：" + e.getMessage());
            return error("业主批量审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 中心批量审核
     */
    @PreAuthorize("@ss.hasPermi('functiontest:TollBridgeStatTest:centerAudit')")
    @Log(title = "收费桥梁统计测试", businessType = BusinessType.UPDATE)
    @PostMapping("/centerAudit/batch")
    public AjaxResult centerAuditBatch()
    {
        try {
            System.out.println("中心批量审核 - 审核所有数据");
            
            // 1. 校验所有数据的review1和review2字段是否都不为空且都为0
            boolean allReview1AndReview2Zero = tollBridgeStatTestService.checkAllReview1AndReview2AreZero();
            if (!allReview1AndReview2Zero) {
                return error("中心批量审核失败：存在未通过实测单位审核或业主审核的数据，请先完成前序审核");
            }
            
            // 2. 批量更新中心审核状态
            int updatedCount = tollBridgeStatTestService.updateReview3ToZero();
            
            System.out.println("中心批量审核完成，更新记录数：" + updatedCount);
            return success("中心批量审核成功，共更新" + updatedCount + "条记录");
        } catch (Exception e) {
            System.err.println("中心批量审核失败：" + e.getMessage());
            return error("中心批量审核失败：" + e.getMessage());
        }
    }

    /**
     * 构建树形结构
     */
    private List<TollBridgeStatTest> buildTree(List<TollBridgeStatTest> list) {
        // 构建父子关系映射
        Map<Long, TollBridgeStatTest> nodeMap = new HashMap<>();
        List<TollBridgeStatTest> rootNodes = new ArrayList<>();
        
        // 先将所有节点放入map中
        for (TollBridgeStatTest node : list) {
            nodeMap.put(node.getId(), node);
        }
        
        // 构建父子关系
        for (TollBridgeStatTest node : list) {
            Long parentId = node.getParentId();
            if (parentId != null && parentId != 0) {
                TollBridgeStatTest parent = nodeMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<TollBridgeStatTest>());
                    }
                    @SuppressWarnings("unchecked")
                    List<TollBridgeStatTest> children = (List<TollBridgeStatTest>) parent.getChildren();
                    children.add(node);
                }
            } else {
                rootNodes.add(node);
            }
        }
        
        return rootNodes;
    }
}
